var app = getApp();
var common = require('../../common/common.js');
var myLon, myLat;
var slideData, navData, supplierData;
var page = 1;
var that;
var canLoad = true;
getSlideData();
getNavData();
getSupplierData();
common.getMyLocation({
    callBack:function (lat,lon) {
        myLon=lon;
        myLat=lat;
    }
})
Page({
    data: {
        indicatorDots: true,
        vertical: false,
        interval: 2000,
        duration: 500
    },
    clickNav: clickNav,
    lower: loadMore,
    onLoad: function (options) {
        that = this;
        that.setData({
            imgUrls: slideData,
            navData: navData,
            supplierData: supplierData,
        })
    }
})
//***********************开始获取数据接口
function getSlideData() {
    var url = "app/ads";
    var data = {
        position_name: "APP置顶广告"
    };
    app.ajaxRequest(url, "get", data, function (ret) {
        slideData = ret.data;
    }, function (err) {
        console.log(err)
    })
}
function getNavData() {
    var url = "app/category/supplier";
    var data = {};
    app.ajaxRequest(url, 'get', data, function (ret, err) {

        navData = ret.data;
    });
}
function loadMore() {
    if (!canLoad) return false;
    canLoad = false;
    page++;
    var that = this;
    var url = "supplier/list?page=" + page;
    var data = {};
    app.ajaxRequest(url, 'get', data, function (ret, err) {
        if (ret.data.length > 0) {
            canLoad = true;
        } else {
            return false;
        }
        var newData = [];
        var oldData = that.data.supplierData;
        for (var i = 0; i < oldData.length; i++) {
            newData.push(oldData[i]);

            if (i == (oldData.length - 1)) {
                for (var i = 0; i < ret.data.length; i++) {
                    var disance="";
                    if(ret.data[i].latitude){
                        disance=common.getTheDisance(myLat,myLon,ret.data[i].latitude,ret.data[i].longitude);
                    }
                    ret.data[i].disance=disance;
                    newData.push(ret.data[i]);
                }
            }
        }


        console.log(newData)
        that.setData({
            supplierData: newData
        })

    });


}
function getSupplierData() {
    var url = "supplier/list";
    var data = {};
    app.ajaxRequest(url, 'get', data, function (ret, err) {


        for(var i=0;i<ret.data.length;i++){
            var disance="";
            if(ret.data[i].latitude){
                disance=common.getTheDisance(myLat,myLon,ret.data[i].latitude,ret.data[i].longitude);
            }
            ret.data[i].disance=disance;
        }
        supplierData = ret.data;
    });
}
//结束接口获取数据*************************
//********************开始页面上的单击方法
function clickNav(event) {
    var link = event.currentTarget.dataset.link;
    console.log(link)
}
//结束页面的单击方法***************


